package com.avcdata.aoscustommade.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avcdata.aoscustommade.R;
import com.avcdata.aoscustommade.bean.LocatityCacheData;
import com.avcdata.aoscustommade.bean.UserRegionBean;
import com.avcdata.aoscustommade.bean.UserRegionBeanChild;
import com.avcdata.aoscustommade.main.BaseActivity;
import com.avcdata.aoscustommade.model.SelectAgencyModel;
import com.avcdata.aoscustommade.presenter.SelectAgencyPresenter;
import com.avcdata.aoscustommade.receiver.MyReceiver;
import com.avcdata.aoscustommade.utils.AppActivityManager;
import com.avcdata.aoscustommade.utils.SharedPreferencesUtils;
import com.avcdata.aoscustommade.utils.TextUitl;
import com.avcdata.aoscustommade.view.MyGrid_View;
import com.avcdata.aoscustommade.view.SelectAgencyView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;

import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Handler;

/**
 * Created by c.c on 2017/3/1.
 * 办事处选择
 */
public class SelectAgency_Activity extends BaseActivity implements SelectAgencyView {
    @ViewInject(R.id.leftImage)
    private ImageView leftImage;
    @ViewInject(R.id.leftText)
    private TextView leftText;
    @ViewInject(R.id.title)
    private TextView title;
    @ViewInject(R.id.expandlistview)
    private ExpandableListView expandlistview;

    @ViewInject(R.id.content_lay)
    private LinearLayout content_lay;
    @ViewInject(R.id.loadfail)
    private View loadfail;


    /**
     * 大区域数据存储
     */
    public ArrayList<UserRegionBean> areaData;
    /**
     * 办事处级数据储存
     */
    private ArrayList<ArrayList<UserRegionBean>> agencyData;
    /**
     * 详情数据存储
     */
    private ArrayList<String> detailData;

    private ArrayList<UserRegionBean> agencyList;

    private ArrayList<String> checkAgencyData;
    private ArrayList<String> checkCityData;

    private SharedPreferencesUtils sp;
    private String stringAre;
    //    private boolean isMain;
    private MyReceiver myReceiver;
    private SelectAgencyPresenter selectAgencyPresenter;


    @Override
    public void initView() {
        setContentView(R.layout.activity_selectagency);
        AppActivityManager.getAppManager().addActivity(this);
        ViewUtils.inject(this);
    }

    @Override
    public void initInstall() {
        sp = new SharedPreferencesUtils(this);
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        myReceiver = new MyReceiver(loadfail);
        this.registerReceiver(myReceiver, filter);
//        isMain = getIntent().getBooleanExtra("isMain",false);

        selectAgencyPresenter = new SelectAgencyPresenter(this, new SelectAgencyModel(SelectAgency_Activity.this));
    }

    @Override
    public void initData() {
        agencyList = new ArrayList<>();
        stringAre = TextUitl.isEmpty(getIntent().getStringExtra("are")) ? "大区" : getIntent().getStringExtra("are");
        title.setText(stringAre);
        int position = getIntent().getIntExtra("position", 0);
        areaData = LocatityCacheData.areaData;
        agencyData = LocatityCacheData.agencyData;
        detailData = LocatityCacheData.detailData;
        if (agencyData != null && agencyData.size() > 0) {
            agencyList = agencyData.get(position);
        }
        checkAgencyData = new ArrayList<>();
        checkCityData = new ArrayList<>();
        loading(true);
        loadDecline();
        expandlistview.setGroupIndicator(null);
//        Agency_Adapter agency_Adapter = new Agency_Adapter();
//        expandlistview.setAdapter(agency_Adapter);
    }

    @Override
    public void evenControl() {
        leftImage.setOnClickListener(this);
        leftText.setOnClickListener(this);

    }

    @Override
    public void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.leftImage:
            case R.id.leftText:
                AppActivityManager.getAppManager().finishActivity(this);
                break;
        }
    }

    private void loading(boolean isLoad) {
        if (isLoad) {
            content_lay.setVisibility(View.GONE);
            loadfail.setVisibility(View.VISIBLE);
        } else {
            content_lay.setVisibility(View.VISIBLE);
            loadfail.setVisibility(View.GONE);
        }
    }


    private void loadingTimeout() {
        loadfail.setVisibility(View.GONE);
        content_lay.setVisibility(View.GONE);
    }


    /**
     * 下降数据
     */
    private void loadDecline() {
        selectAgencyPresenter.loadDecline(sp.getNewWeek(), detailData);

    }

    //查询下降数据成功
    @Override
    public void loadDeclineSuccess(JSONObject jsonObject) {
        ArrayList<String> checkAgencyDataTemp = new ArrayList<>();
        ArrayList<String> checkCityDataTemp = new ArrayList<>();
        try {
            if (!TextUitl.isEmpty(jsonObject.toString())) {
                boolean success = jsonObject.getBoolean("success");
                if (success && jsonObject.has("returnValue")) {
                    JSONObject returnValueObject = jsonObject.getJSONObject("returnValue");
                    Iterator iterator = returnValueObject.keys();
                    while (iterator.hasNext()) {
                        String key = iterator.next().toString().trim();
                        String value = returnValueObject.getString(key).trim();
                        if (!TextUitl.isEmpty(value)) {
                            JSONObject areObject = new JSONObject(value);
                            Iterator iteratorAre = areObject.keys();
                            while (iteratorAre.hasNext()) {
                                String keyAgency = iteratorAre.next().toString().trim();
                                String valueAgency = areObject.getString(keyAgency).trim();
                                checkAgencyDataTemp.add(keyAgency);
//                                        checkCityDataTemp.add(keyAgency);
                                if (!TextUitl.isEmpty(valueAgency)) {
                                    JSONArray cityArray = new JSONArray(valueAgency);
                                    for (int j = 0, k = cityArray.length(); j < k; j++) {
                                        checkCityDataTemp.add(cityArray.get(j).toString().trim());
                                    }
                                }
                            }
                        }
                    }
                    checkAgencyData = checkAgencyDataTemp;
                    checkCityData = checkCityDataTemp;
                    loadedType(true);
                } else {
                    loadedType(false);
                }
            }
            loading(false);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //查询下降数据失败
    @Override
    public void loadDeclineFailure() {
        loadedType(false);
        loading(false);
    }

    //查询下降数据失败
    @Override
    public void loadDeclineFailure(Throwable throwable) {
        if (throwable instanceof ConnectTimeoutException ||
                throwable instanceof SocketTimeoutException){
            loadingTimeout();
            loading(false);
        }
    }

    private void loadedType(boolean isSuccess) {
        if (isSuccess) {
            Agency_Adapter agency_Adapter = new Agency_Adapter();
            expandlistview.setAdapter(agency_Adapter);
        }

    }

    /**
     * 办事处适配器
     */
    private class Agency_Adapter extends BaseExpandableListAdapter {
        public Handler handler;

//        public Agency_Adapter() {
//            handler = new Handler() {
//
//            };
//        }


        public void refresh() {
            notifyDataSetChanged();
        }


        @Override
        public int getGroupCount() {
            return agencyList.size();
        }

        @Override
        public long getGroupId(int groupPosition) {
            return 0;
//            return groupPosition;
        }

        @Override
        public Object getGroup(int groupPosition) {
            return getGroup(groupPosition);
        }

        @Override
        public int getChildrenCount(int groupPosition) {
//            if (agencyList.get(groupPosition).getDeChilds().size() != 0) {
//                return agencyList.get(groupPosition).getDeChilds().size();
//            } else {
//                return 0;
//            }
            return 1;
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return agencyList.get(groupPosition).getDeChilds().get(childPosition);
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return 0;
//            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @SuppressWarnings("deprecation")
        @SuppressLint("InflateParams")
        @Override
        public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            ViewHolderGroup vHolder = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(SelectAgency_Activity.this).inflate(R.layout.item_selectarea, null);
                vHolder = new ViewHolderGroup();
                vHolder.user_line = (ImageView) convertView.findViewById(R.id.user_line);
                vHolder.area_name = (TextView) convertView.findViewById(R.id.area_name);
                vHolder.area_state = (TextView) convertView.findViewById(R.id.area_state);
                convertView.setTag(vHolder);
            } else {
                vHolder = (ViewHolderGroup) convertView.getTag();
            }
            UserRegionBean userRegionBean = agencyList.get(groupPosition);
            vHolder.user_line.setVisibility(View.VISIBLE);
            vHolder.area_name.setText(userRegionBean.getLandName());

            //区域状态
            vHolder.area_state.setVisibility(View.VISIBLE);

            if (isAgencyDecline(userRegionBean.getLandName())) {
                vHolder.area_state.setVisibility(View.VISIBLE);
                vHolder.area_name.setTextColor(getResources().getColor(R.color.red));

            } else {
                vHolder.area_state.setVisibility(View.GONE);
                vHolder.area_name.setTextColor(getResources().getColor(R.color.text_one));
            }

            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (expandlistview.isGroupExpanded(groupPosition)) {
                        expandlistview.collapseGroup(groupPosition);
                    } else {
                        collapseAllGroup();
                        expandlistview.expandGroup(groupPosition, true);

                    }
                }
            });

            notifyDataSetChanged();
            return convertView;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            ViewHolderChild vHolder = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(SelectAgency_Activity.this).inflate(R.layout.single_gridviewscroll, null);
                vHolder = new ViewHolderChild();
                vHolder.gridview_scroll = (MyGrid_View) convertView.findViewById(R.id.gridview_scroll);
                convertView.setTag(vHolder);
            } else {
                vHolder = (ViewHolderChild) convertView.getTag();
            }

            ArrayList<UserRegionBeanChild> dataChild = agencyList.get(groupPosition).getDeChilds();
            final AgencyChild_Adapter agencyChild_adapter = new AgencyChild_Adapter(dataChild, agencyList.get(groupPosition).getLandName());
            vHolder.gridview_scroll.setAdapter(agencyChild_adapter);

//            convertView.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//
//
//                }
//            });

//            notifyDataSetChanged();
            return convertView;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return false;
        }

    }

    //关闭所有的Group
    private void collapseAllGroup() {
        for (int i = 0, j = agencyList.size(); i < j; i++) {
            expandlistview.collapseGroup(i);
        }
    }


    /**
     * 子类适配器
     */
    private class AgencyChild_Adapter extends BaseAdapter {

        private ArrayList<UserRegionBeanChild> dataChild;
        private String stringAgency;

        private AgencyChild_Adapter(ArrayList<UserRegionBeanChild> dataChild, String stringAgency) {
            super();
            this.dataChild = dataChild;
            this.stringAgency = stringAgency;
        }

        @Override
        public int getCount() {
            return dataChild.size();
        }

        @Override
        public Object getItem(int position) {
            return dataChild.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @SuppressWarnings("deprecation")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolderGridChild vHolder = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(SelectAgency_Activity.this).inflate(R.layout.item_citybutton, null);
                vHolder = new ViewHolderGridChild();
                vHolder.child_button = (Button) convertView.findViewById(R.id.child_button);
                convertView.setTag(vHolder);
            } else {
                vHolder = (ViewHolderGridChild) convertView.getTag();
            }
            final UserRegionBeanChild tempUserBean = dataChild.get(position);

            vHolder.child_button.setText(tempUserBean.getLandName());


            if (isCityDecline(tempUserBean.getLandName())) {
                vHolder.child_button.setBackgroundResource(R.drawable.bg_childred);
                vHolder.child_button.setTextColor(getResources().getColor(R.color.red));

            } else {
                vHolder.child_button.setBackgroundResource(R.drawable.bg_childgray);
                vHolder.child_button.setTextColor(getResources().getColor(R.color.text_two));
            }

            vHolder.child_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(SelectAgency_Activity.this, CitySelect_Activity.class);
                    intent.putExtra("are", stringAre);
                    intent.putExtra("agency", stringAgency);
                    intent.putExtra("city", tempUserBean.getLandName());
//                    intent.putExtra("isMain", isMain);
                    startActivity(intent);

                }
            });

//            notifyDataSetChanged();
            return convertView;
        }
    }


    private boolean isAgencyDecline(String string) {
        if (checkAgencyData.size() != 0) {
//            for (int i = 0, j = checkAgencyData.size(); i < j; i++) {
            if (checkAgencyData.contains(string)) {
                return true;
            }
//            }
        }
        return false;
    }


    private boolean isCityDecline(String string) {
        if (checkCityData.size() != 0) {
            for (int i = 0, j = checkCityData.size(); i < j; i++) {
                if (checkCityData.contains(string)) {
                    return true;
                }
            }
        }

        return false;
    }


    public class ViewHolderGroup {
        private ImageView user_line;
        private TextView area_name;
        private TextView area_state;

    }

    public class ViewHolderChild {
        private MyGrid_View gridview_scroll;
    }

    public class ViewHolderGridChild {
        private Button child_button;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(myReceiver);
    }


}
